import http from "@/utils/http"
import * as types from "../actionTypes"
import { setToken as updateToken, clearToken } from "@/utils"
// action creator
const setToken = (payload) => ({ type: types.SETTOKEN, payload })
const setUserInfo = (payload) => ({ type: types.SETUSERINFO, payload })
const clearTokenInfo = () => ({ type: types.CLEARTOKEN })
// 异步的action
// data是登录的手机号和验证码
export const login = (data) => {
  return async (dispatch, getState) => {
    // 异步请求
    const { token } = await http({
      method: "post",
      url: "/authorizations",
      data,
    })
    // 拿到token之后
    updateToken(token) // 写入前端缓存 设置前端缓存
    // localStorage.setItem("geek-pc-token", updateToken) // 写入前端缓存
    dispatch(setToken(token)) // 分发action
  }
}

// dispatch({  type: '' })
// dispatch((dispatch, getState) => {})

export const getUserInfo = () => {
  return async (dispatch) => {
    const data = await http({
      url: "/user/profile",
    })
    // 派发action
    dispatch(setUserInfo(data))
  }
}
export const logout = () => {
  return (dispatch) => {
    // 调用清空token
    clearToken() // 清空缓存
    dispatch(clearTokenInfo()) // 清空redux
  }
}
